<?php

// +----------------------------------------------------------------------
// | User模型
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\model\ucenter;

use app\cloud\model\ProductAuth;
use app\cloud\model\Product;
use app\model\file\Image;
use app\forum\model\Attitude;
use app\forum\model\Collection;
use app\forum\model\Post;
use app\forum\model\PostComment;
use app\event\im\Chat as ChatEvent;
use app\model\im\Chat;
use app\model\pos\Bill;
use app\model\pos\Pos;
use app\model\pos\PosOrder;
use app\model\pos\PosTrade;
use app\model\pos\PosTransfer;
use app\model\pos\UserPosVip;
use app\model\store\StoreApp;
use app\pay\model\CouponCard;
use app\pay\model\UserBalance;
use app\pay\model\UserBalanceAccount;
use app\pay\model\UserBalanceCash;
use app\pay\model\UserBalanceRecharge;
use app\model\store\Address;
use app\model\store\Cart;
use app\model\store\Distribution;
use app\model\store\Good;
use app\model\store\GoodEvaluate;
use app\model\store\GoodVisit;
use app\model\store\Store;
use app\model\store\StoreAuth;
use app\model\ucenter\Common as CommonModel;
use app\model\store\Order;
use think\facade\Config;

class User extends CommonModel
{

    public $sex_list = [
        '0' => '保密',
        '1' => '男',
        '2' => '女'
    ];

    public function teams()
    {
        return $this->belongsTo(User::class, 'bid');
    }

    public function carts()
    {
        return $this->hasMany(Cart::class);
    }

    public function tasks()
    {
        return $this->belongsTo(UserTask::class);
    }

    public function ip()
    {
        return $this->belongsTo(IpPool::class, 'create_ip', 'ip');
    }

    public function pidUser()
    {
        return $this->belongsTo(User::class, 'pid', 'id');
    }

    public function moneys()
    {
        return $this->hasMany(UserMoneyLog::class, 'user_id');
    }

    public function bills()
    {
        return $this->hasMany(Bill::class, 'user_id');
    }

    public function trades()
    {
        return $this->hasMany(PosTrade::class, 'user_id');
    }

    public function poses()
    {
        return $this->hasMany(Pos::class);
    }

    public function posOrders()
    {
        return $this->hasMany(PosOrder::class);
    }

    public function posVip()
    {
        return $this->hasOne(UserPosVip::class)->order('id DESC');
    }

    /**
     * 划拨记录
     * @return \think\model\relation\HasMany
     */
    public function posTransfers()
    {
        return $this->hasMany(PosTransfer::class);
    }

    /**
     * 我的购物车
     */
    public function addresses()
    {
        return $this->hasMany(Address::class)->where('status', 1);
    }

    /**
     * 评价
     */
    public function evaluates()
    {
        return $this->hasMany(GoodEvaluate::class);
    }

    ////******store模块 end******/////////


    /**
     * 我的积分记录
     */
    public function points()
    {
        return $this->hasMany(UserPoint::class);
    }

    /**
     * 我的经验记录
     */
    public function experiences()
    {
        return $this->hasMany(UserExperience::class);
    }


    /**
     * 我的消息
     */
    public function messages()
    {
        return $this->hasMany(Message::class);
    }


    /**
     * 我的直推邀请
     * @author  : 微尘 <yicmf@qq.com>
     * @datetime: 2019/1/23 15:39
     */
    public function invites()
    {
        return $this->hasMany(User::class, 'invite_id');
    }

//    /**
//     * 头像
//     */
//    public function avatar()
//    {
//        return $this->belongsTo(Image::class, 'avatar_id')->field('id,url,save_name,driver');
//    }

    /**
     * 等级
     * @return \think\model\relation\BelongsTo
     */
    public function grade()
    {
        return $this->belongsTo(UserGrade::class, 'user_grade_id');
    }

    /**
     * 我的直推邀请
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function invite()
    {
        return $this->belongsTo(User::class, 'invite_id');
    }

    /**
     * 我的第三方授权
     * @return \think\model\relation\HasMany
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function oauths()
    {
        return $this->hasMany(UserOauth::class);
    }

    /**
     * 登录信息
     */
    public function tokens()
    {
        return $this->hasMany(UserToken::class);
    }

    /**
     * 我的实名认证
     */
    public function auths()
    {
        return $this->hasMany(UserAuth::class);
    }

    /**
     * 我的签到
     */
    public function signs()
    {
        return $this->hasMany(UserSign::class);
    }

    /**
     * 用户后台角色
     */
    public function roles()
    {
        return $this->belongsToMany(AuthGroup::class, AuthGroupAccess::class);
    }

    /**
     * 用户标签
     */
    public function tags()
    {
        return $this->belongsToMany(Tag::class, UserTag::class);
    }


    public function logs()
    {
        return $this->hasMany(ActionLog::class);
    }

    /**
     * 提现账户
     */
    public function accounts()
    {
        return $this->hasMany(UserBalanceAccount::class);
    }

    /**
     * 用户账户余额变更记录
     */
    public function balances()
    {
        return $this->hasMany(UserBalance::class);
    }

    /**
     * 充值记录
     */
    public function recharges()
    {
        return $this->hasMany(UserBalanceRecharge::class);
    }

    /**
     * 在线记录
     * @return \think\model\relation\HasMany
     * @author  : 微尘 <yicmf@qq.com>
     * @datetime: 2019/3/11 12:19
     */
    public function onlines()
    {
        return $this->hasMany(UserOnline::class);
    }

    /**
     * 提现
     */
    public function cashes()
    {
        return $this->hasMany(UserBalanceCash::class);
    }

    /**
     * 新增修改
     * @param $data
     */
    public static function onBeforeInsert($data)
    {
        $data['status'] = 1;
        $data['short_code'] = isset($data['short_code']) ? $data['short_code'] : 'st' . uniqid();;
        $data['create_ip'] = request()->ip();
        $data['joinip'] = request()->ip();
//        $data['agent'] = request()->server('HTTP_USER_AGENT');
    }

    /**
     * 更新修改
     * @param $data
     */
    public static function onBeforeUpdate($data)
    {

        $data['initial'] = !empty($data['nickname_remark']) ? get_first_char($data['nickname_remark']) : get_first_char($data['nickname']);
    }

    // 类型转换
    protected $type = [
        'push_arr' => 'array',
        'privacy_setting' => 'array',
    ];

    public function getIsOnlineAttr($value, $data): int
    {
        // 判断用户是否在线
        return ChatEvent::isOnline($data['id']);
    }

//    public function getIdCardAttr($value, $data): int
//    {
//        dump($data);
//        // 判断用户是否在线
//    }

//    public function getMobileAttr($value, $data)
//    {
//        return secrecy_show($value);
//    }

    /**
     * 活跃时间
     * @param $value
     * @param $data
     * @return string
     * @author  : 微尘 <yicmf@qq.com>
     * @datetime: 2019/3/7 9:09
     */
    public function getLastActiveTimeTextAttr($value, $data)
    {
        $strap = strtotime($data['last_active_time']);
        if ($strap > strtotime('-10 minute')) {
            return '在线';
        } elseif ($strap > strtotime('-1 hours')) {
            return '刚刚在线';
        } elseif ($strap > strtotime('-1 day')) {
            return '近期在线';
        } elseif ($strap > strtotime('-1 week')) {
            return '本周活跃';
        } elseif ($strap > strtotime('-1 month')) {
            return '本月活跃';
        } elseif ($strap > strtotime('-1 year')) {
            return '今年活跃';
        } else {
            return '不活跃';
        }
    }

    public function getBirthdayAttr($value, $data)
    {
        return $value ? time_format($value, 'Y-m-d') : '';
    }

    public function getHomeAnalyticsAttr($value)
    {
        return htmlspecialchars_decode($value);
    }


    public function getBalanceAttr($value)
    {
        return floor($value * 100) / 100;
//            return sprintf("%.2f", $value);
    }

    public function getAvatarUrlAttr($value, $data)
    {
        if ($value) {
            return $value;
        } else {
            if (!empty($data['avatar_id'])) {
                return get_image($data['avatar_id'], 'url');
            } else {
                return '';
            }
        }
//            return sprintf("%.2f", $value);
    }

    public function getAvatarAttr($value, $data)
    {
        if (strpos($value, 'https://admin.mayichuangye168.com') !== false) {
            return str_replace('https://admin.mayichuangye168.com', request()->domain(), $value);
        } elseif (strpos($value, '/uploads/') === 0) {
            return request()->domain().$value;
        } else {
            return $value;
        }
//            return sprintf("%.2f", $value);
    }

    public function getGroupTitleAttr($value, $data)
    {
        if ($value) {
            return $value;
        } else {
            if (!empty($data['master_auth_group_id'])) {
                return AuthGroup::where('id', $data['master_auth_group_id'])->value('title');
            } else {
                return '';
            }
        }
//            return sprintf("%.2f", $value);
    }

    public function getIncomeBalanceAttr($value)
    {
        return floor($value * 100) / 100;
    }

//    public function getStatusAttr($value)
//    {
//        if ($value == 'normal') {
//            return 1;
//        } else {
//            return 0;
//        }
//    }


    public function getLevelAttr($value)
    {
        if ($value >3) {
            return 3;
        } else {
            return $value;
        }
    }

    public function getPidAttr($value)
    {
        return $value?:38;
    }

        public function getCreateTimeAttr($value,$data)
        {
            return $value?$value:date('Y-m-d H:i:s',$data['createtime']);
        }
    public function getBidAttr($value)
    {
        return $value?:38;
    }

    public function getFreezeBalanceAttr($value)
    {
        return floor($value * 100) / 100;
    }

    protected function setPasswordAttr($value)
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }

    protected function setPayPasswordAttr($value)
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }

    protected function setAccountAttr($value)
    {
        return $value ? $value : ('ld' . uniqid());
    }

    protected function setInitialAttr($value, $data)
    {
        return !empty($data['nickname_remark']) ? get_first_char($data['nickname_remark']) : get_first_char($data['nickname']);
    }

    protected function setSexAttr($value)
    {
        return isset($value) ? $value : 2;
    }

}
